import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoServer {
    private ServerSocket serverSocket;

    public TcpEchoServer(int port) throws IOException {
        serverSocket=new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("start");
        //线程池
        ExecutorService pool= Executors.newCachedThreadPool();
        while(true){
            Socket clientSocket=serverSocket.accept();

            pool.submit(new Runnable() {
                @Override
                public void run() {
                    processConnection(clientSocket);
                }
            });
        }
    }
    public void processConnection(Socket clientSocket){
        System.out.printf("客户端[%s:%d]上线！\n",clientSocket.getInetAddress(),
                clientSocket.getPort());
        try(InputStream inputStream=clientSocket.getInputStream();
            OutputStream outputStream=clientSocket.getOutputStream()){

            while(true){
                Scanner sc=new Scanner(inputStream);
                if(!sc.hasNext()){
                    System.out.printf("客户端[%s:%d]下线！\n",clientSocket.getInetAddress(),
                            clientSocket.getPort());
                }
                //1.读取请求
                String request=sc.next();
                //2.处理请求
                String response=process(request);
                //3.返回响应
                PrintWriter writer=new PrintWriter(outputStream);
                writer.println(response);
                writer.flush();
                //打印日志
                System.out.printf("[%s:%d]req:%s,resp:%s\n",clientSocket.getInetAddress(),
                        clientSocket.getPort(),request,response);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            try {
                clientSocket.close();
            }catch (IOException e){
                throw new RuntimeException(e);
            }
        }
    }
    public String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server=new TcpEchoServer(10200);
        server.start();
    }
}
